<template>
  <div>
    About
    <ul>
      <li v-for="item in list" :key="item.filmId">
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      list: [],
    };
  },

  methods: {
    fetchData() {
      const response = axios.get(
        "https://m.maizuo.com/gateway?cityId=440300&pageNum=1&pageSize=10&type=1&k=586515",
        {
          headers: {
            "X-Host": "mall.film-ticket.film.list",
          },
        }
      );
      console.log(response);
    },
  },

  created() {
    console.log("created");
  },

  mounted() {
    console.log("mounted");
  },

  /**
   * 组件内守卫进入
   *  1. 无法获取到 组件的实例 this
   *    可以给 next() 传递一个回调函数，回调函数可以接受一个 vm 的参数，该参数是当前组件的实例对象
   */
  beforeRouteEnter(to, from, next) {
    console.log("beforeRouteEnter");

    axios
      .get(
        "https://m.maizuo.com/gateway?cityId=440300&pageNum=1&pageSize=10&type=1&k=586515",
        {
          headers: {
            "X-Host": "mall.film-ticket.film.list",
          },
        }
      )
      .then((response) => {
        // 根据接口的情况来控制是否需要 next()
        const {
          data: {
            status,
            data: { films },
          },
        } = response;

        if (status !== 0) {
          // 接口有问题，next('/login')
          next("/login");
        } else {
          next((vm) => {
            vm.list = films;
          });
        }
      });
  },

  beforeRouteUpdate(to, from, next) {
    console.log("beforeRouteUpdate");
    next();
  },

  /**
   * 应用场景：
   *    1. 可以做离开的二次确认功能
   */
  beforeRouteLeave(to, from, next) {
    console.log("beforeRouteLeave");

    const isOk = window.confirm("请确认是否真的要离开呀");
    if (isOk) {
      next();
    } else {
      next(false);
    }
  },
};
</script>
